package com.example.project.activity.mingxi;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.VolleyError;
import com.example.project.MyApplication;
import com.example.project.R;
import com.example.project.activity.tubiao.MonthChartActivity;
import com.example.project.activity.jizhang.RecordActivity;
import com.example.project.activity.wode.WdActivity;
import com.example.project.adapter.AccountAdapter;
import com.example.project.bean.AccountBean;
import com.example.project.bean.TypeBean;
import com.example.project.dialog.BudgetDialog;
import com.example.project.okhttp.OkHttpClientManager;
import com.example.project.tool.SharePreferce;
import com.example.project.volley.ConstantUtil;
import com.example.project.volley.Params;
import com.example.project.volley.VolleyInterface;
import com.example.project.volley.VolleyRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
//主页面
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView Ivjz,Ivbb,Ivzj,Ivwd;//下方跳转的控件
    private ImageView showYj; //切换明文和密文
    private LinearLayout llZd,llYs; //目录账单和预算
    boolean isShow=true; //true为显示，false为隐藏
    private TextView srComment,zcComment,ysComment,tvZcs,tvTime,tvjz; //收入，支出，预算金额,今日支出，今日时间,改变下方控件颜色
    private ListView list; //账单列表
    AccountAdapter adapter; //列表适配器
    List<AccountBean> mDatas; //声明数据源
    int year,month,day,mainId; //年，月，日,用户id（int）
    String years,months,days,mainIds; //年，月，日,用户id（String）
    SharedPreferences preferences; //共享参数（暂存类）

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );
        initView();
        setInitTime();
        getList();
    }


    // 当activity获取焦点时，会调用的方法
    @Override
    protected void onResume() {
        super.onResume();
        int notificationId = getIntent().getIntExtra("notification", 123);
        if (notificationId != 123) {
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            //移除标记为id的通知 (只是针对当前Context下的所有Notification)
            notificationManager.cancel(notificationId);
            //移除所有通知
            //notificationManager.cancelAll();
        }
    }

    //实例化数据
    private void initView() {
        mDatas=new ArrayList<>(  );
        llZd=findViewById( R.id.ll_zd );
        llZd.setOnClickListener( this );
        llYs=findViewById( R.id.ll_ys );
        llYs.setOnClickListener( this );

        Ivjz=findViewById( R.id.Iv_jz );
        Ivjz.setOnClickListener( this );
        Ivbb=findViewById( R.id.Iv_bb );
        Ivbb.setOnClickListener( this );
        Ivzj=findViewById( R.id.Iv_zj );
        Ivzj.setOnClickListener( this );
        Ivwd=findViewById( R.id.Iv_wd );
        Ivwd.setOnClickListener( this );
        srComment=findViewById( R.id.tv_sr_comment );
        srComment.setOnClickListener( this );
        zcComment=findViewById( R.id.tv_zc_comment );
        zcComment.setOnClickListener( this );
        ysComment=findViewById( R.id.tv_ys_comment );
        ysComment.setOnClickListener( this );
        showYj=findViewById( R.id.iv_yj );
        showYj.setOnClickListener( this );

        tvTime=findViewById( R.id.tv_time );
        tvZcs=findViewById( R.id.tv_zcs );
        tvjz=findViewById( R.id.tv_jz );
        list=findViewById( R.id.lv_list );
        Ivjz.setImageResource( R.drawable.mxb);
        tvjz.setTextColor( Color.parseColor("#87CEFA") );
        preferences = getSharedPreferences("budget", Context.MODE_PRIVATE);
        mainId= MyApplication.getMainId(); //获取用户信息
        mainIds=mainId+"";

    }

    //获取当前时间，显示出来
    private void setInitTime() {
        Date date=new Date(  );  //实例化时间
        SimpleDateFormat sdf=new SimpleDateFormat( "yyyy年MM月dd日 HH:mm" ); //设置时间格式
        String time=sdf.format( date ); //加载时间格式
        tvTime.setText( time ); //设置时间
        Calendar calendar=Calendar.getInstance(); //实例化日历
        year=calendar.get( calendar.YEAR ); //获取日历的年
        month=calendar.get( calendar.MARCH )+1; //获取日历的月
        day=calendar.get( calendar.DAY_OF_MONTH ); //获取日历的天
        years=year+"";
        months=month+"";
        days=day+"";
        mainIds=mainId+"";
        volleyTimeInfo(years,months,mainIds);
        volleyList(years,months,days,mainIds);
    }

    /* 获取当月的收入和支出 （记账总钱数）*/
    private void volleyTimeInfo(String year,String month,String mainId) {
        VolleyInterface vif=null;
        VolleyRequest.RequesetPost( ConstantUtil.MONTHSR, "MONTHInfo", Params.MonthList(year,month,mainId),new VolleyInterface( this ){
            @Override
            public void onMySuccess(String jsonStr) {
                System.out.println("数据:"+jsonStr);
                JSONObject jsonObject = null;
                try {
                    jsonObject =new JSONObject( jsonStr );
                    String inMoney=jsonObject.getString( "inMoney" );
                    String outMoney=jsonObject.getString( "outMoney" );
                    String budget=jsonObject.getString( "budget" );
                    float ys=Float.parseFloat(budget)-Float.parseFloat(outMoney);
                    ysComment.setText(ys+"");
                    srComment.setText(inMoney);
                    zcComment.setText(outMoney);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onMyError(VolleyError error) {
                Toast.makeText(MainActivity.this, "获取信息失败", Toast.LENGTH_LONG).show();
            }
            @Override
            public void onImageSuccess(Bitmap bitmap) {

            }
        });
    }

    //查询主页的list列表
    private void volleyList(String year,String month,String day,String mainId) {
        VolleyInterface vif=null;
        VolleyRequest.RequesetPost( ConstantUtil.List, "List", Params.List(year,month,day,mainId),new VolleyInterface( this ){
            @Override
            public void onMySuccess(String jsonStr) throws JSONException {
                JSONObject json = new JSONObject(jsonStr);
                JSONArray dataArray = json.getJSONArray("data");
                if(dataArray!=null){
                    // 初始化list数组对象
                    ArrayList<AccountBean> list = new ArrayList<>();
                    for (int i = 0; i < dataArray.length(); i++) {
                        JSONObject juser = dataArray.getJSONObject(i);
                        System.out.println("juser数据:"+ juser);
                        AccountBean accountBean=new AccountBean(  );
                        accountBean.setId( Integer.parseInt( juser.getString( "id" ) ) );
                        accountBean.setTypename( juser.getString( "typename" ) );
                        accountBean.setsImageId( Integer.parseInt(juser.getString( "sImageId" )) );
                        if(juser.getString( "beizhu").equals( "null" )){
                            accountBean.setBeizhu("");
                        }else {
                            accountBean.setBeizhu( juser.getString( "beizhu" )  );
                        }
                        accountBean.setMoney( Float.parseFloat( juser.getString( "money" ) ) );
                        accountBean.setTime( juser.getString( "time" ) );
                        accountBean.setYear( Integer.parseInt( juser.getString( "year" ) ) );
                        accountBean.setMonth( Integer.parseInt( juser.getString( "month" ) ) );
                        accountBean.setDay( Integer.parseInt( juser.getString( "day" ) ) );
                        accountBean.setKind( Integer.parseInt( juser.getString( "kind" ) ) );
                        accountBean.setMainId( Integer.parseInt( juser.getString( "mainId" ) ) );

                        list.add( accountBean );
                        mDatas.clear(); //清楚列表信息
                        mDatas.addAll(list); //将信息添加到列表里
                        adapter.notifyDataSetChanged(); //更新
                        setLVLongClickListener(); // 设置ListView的点击事件
                    }
                }


            }

            @Override
            public void onMyError(VolleyError error) {
                Toast.makeText(MainActivity.this, "获取信息失败", Toast.LENGTH_LONG).show();
            }
            @Override
            public void onImageSuccess(Bitmap bitmap) {

            }
        });
    }

    //list获取数据
    private void getList() {
        ArrayList<TypeBean> typeList=new ArrayList<>(  );
        typeList.add( new TypeBean(  ) );
        //设置适配器
        adapter=new AccountAdapter( MainActivity.this,mDatas );
        list.setAdapter( adapter );
    }

    //切换明文和密文
    private void toggleShow() {
        if (isShow) {   //明文====》密文
            PasswordTransformationMethod passwordMethod = PasswordTransformationMethod.getInstance();
            srComment.setTransformationMethod(passwordMethod);   //设置隐藏
            zcComment.setTransformationMethod(passwordMethod);   //设置隐藏
            ysComment.setTransformationMethod(passwordMethod);   //设置隐藏
            showYj.setImageResource(R.drawable.by);
            isShow = false;   //设置标志位为隐藏状态
        }else{  //密文---》明文
            HideReturnsTransformationMethod hideMethod = HideReturnsTransformationMethod.getInstance();
            srComment.setTransformationMethod(hideMethod);   //设置隐藏
            zcComment.setTransformationMethod(hideMethod);   //设置隐藏
            ysComment.setTransformationMethod(hideMethod);   //设置隐藏
            showYj.setImageResource(R.drawable.yj);
            isShow = true;   //设置标志位为隐藏状态
        }
    }

    /** 显示预算设置对话框*/
    private void showBudgetDialog() {
        BudgetDialog dialog = new BudgetDialog(this); //实例化对话框
        dialog.show(); //显示对话框
        dialog.setDialogSize(); //动态的设置弹出框大小的方法
        dialog.setOnEnsureListener(new BudgetDialog.OnEnsureListener() {
            @Override
            public void onEnsure(float money) {
                String moneys=String.valueOf(money);
                volleyUpdateMoney(mainIds,moneys);
            }
        });
    }

    //设置预算网络请求
    public void volleyUpdateMoney(String mainIds,String money) {
        VolleyRequest.RequesetPost(ConstantUtil.UPDATEMONEY, "UpdateMoney", Params.GetString2(mainIds,money), new VolleyInterface(this) {

            @Override
            public void onMySuccess(String result) {
                if(!result.equals("1")){
                    Toast.makeText(MainActivity.this, "设置失败", Toast.LENGTH_LONG).show();
                }
                Toast.makeText(MainActivity.this,"设置成功",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onMyError(VolleyError error) {
                Toast.makeText(MainActivity.this,"网络不好！！！",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onImageSuccess(Bitmap bitmap) {

            }
        });

    }

    //设置ListView的点击事件，修改和删除
    private void setLVLongClickListener() {
        list.setOnItemClickListener( new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AccountBean clickBean = mDatas.get(position);  //获取正在被点击的这条信息
                Intent intent=new Intent( MainActivity.this, MessageActivity.class );
                int Id=clickBean.getId();
                int sImageId=clickBean.getsImageId();
                String typeName=clickBean.getTypename();
                float money=clickBean.getMoney();
                String beizhu=clickBean.getBeizhu();
                String time=clickBean.getTime();
                int kind=clickBean.getKind();
                intent.putExtra( "Id",String.valueOf( Id ));
                intent.putExtra( "money",String.valueOf( money ) );
                intent.putExtra( "sImageId",String.valueOf( sImageId ) );
                intent.putExtra( "type",typeName );
                intent.putExtra( "beizhu",beizhu );
                intent.putExtra( "time",time );
                intent.putExtra( "kind",String.valueOf( kind ) );
                startActivity( intent );

            }
        } );
    }

    /* 点击事件*/
    public void onClick(View view) {
        Intent intent=null;
        switch (view.getId()) {
            case R.id.ll_zd:
                intent=new Intent( MainActivity.this, HistoryActivity.class );
                startActivity( intent );
                break;
            case R.id.ll_ys:
                showBudgetDialog();
                break;
            case R.id.iv_yj:
                //切换明文和密文
                toggleShow();
                break;
            case R.id.Iv_bb:
                intent=new Intent(this, MonthChartActivity.class);
                startActivity( intent );
                break;
            case R.id.Iv_zj:
                intent=new Intent(this, RecordActivity.class);
                startActivity( intent );
                break;
            case R.id.Iv_wd:
                intent=new Intent(this, WdActivity.class);
                startActivity( intent );
                break;
        }
    }

}